package com.zkh.myutils.io.excel.data;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 行数据对象
 */
public class RowData {
	//列数据
	private List<CellData> colList;
	//关联Sheet
	private SheetData sheetData;
	
	public RowData(SheetData sheetData) {
		this.colList = new ArrayList<>();
		this.sheetData = sheetData;
	}
	
	public RowData(List<CellData> colList, SheetData sheetData) {
		this.colList = colList;
		this.sheetData = sheetData;
	}
	
	/**
	 * 遍历列
	 * @param biConsumer 自定义处理方法
	 */
	public void eachCol(BiConsumer<CellData, Integer> biConsumer) {
		//遍历列数据
		for(int i=0,len=sheetData.getCols(); i<len; i++) {
			biConsumer.accept(colList.size()>i ? colList.get(i) : CellData.EMPTY_CELLDATA, i);
		}
	}
	
	/**
	 * 列对象转Stream
	 * @return 列Stream
	 */
	public Stream<CellData> colStream(){
		//行数据
		CellData[] cellDatas = new CellData[sheetData.getCols()];
		//赋值
		eachCol((c,i)->cellDatas[i] = c);
		//返回流
		return Stream.of(cellDatas);
	}
	
	/**
	 * 合并列数据，将当前单元格值设置为上一个单元格值
	 * @param index 当前单元格索引
	 */
	public CellData setPreData(int index) {
		//克隆单元格
		CellData cellData = CellData.clone(colList.get(index-1));
		//保存单元格
		colList.set(index, cellData);
		//返回新单元格
		return cellData;
	}
	
	/**
	 * 设置单元格值
	 * @param cellData 单元格对象
	 * @param index 要设置的索引
	 */
	public void setCellData(CellData cellData, int index) {
		colList.set(index, cellData);
	}
	
	/**
	 * 获取单元格对象
	 * @param index 索引
	 * @return 单元格对象
	 */
	public CellData getCellData(int index) {
		return index>colList.size()-1 ? CellData.EMPTY_CELLDATA : colList.get(index);
	}
	
	@Override
	public String toString() {
		return "[" + colStream().map(CellData::getStringValue).collect(Collectors.joining(", ")) + "]";
	}
}
